package com.lang.datahandler.handler;

import com.lang.constrants.DatasourceConstrants;
import com.lang.datahandler.service.DatasourceHandler;
import com.lang.datahandler.utils.DynamicDataSource;
import com.lang.dto.datasource.BaseDataSourceDto;
import com.lang.dto.datasource.MysqlDto;
import com.lang.exception.BaseException;
import com.lang.exception.datasource.DataSourceExceptionEnum;
import org.springframework.stereotype.Component;

/**
 * creat by SimonLang
 * 2022/12/30 19:42
 */

@Component
public class MysqlHandler implements DatasourceHandler {

    private DynamicDataSource dynamicDataSource = DynamicDataSource.getInstance();
    @Override
    public boolean preconnect(BaseDataSourceDto baseDataSourceDto) {
        // 1.向下转型
        MysqlDto mysqlDto = (MysqlDto) baseDataSourceDto;
        // 2.拆分ip和port
        String ipPort = mysqlDto.getHostPort();
        String ip = ipPort.split(":")[0];
        String port = ipPort.split(":")[1];
        // 3.url拼接
        String url = String.format(DatasourceConstrants.MYSQL_URL,ip,port,mysqlDto.getDbName());
        // 4. 使用DruidDatasource进行测试连接
        try {
            dynamicDataSource.connect(url,baseDataSourceDto);
        }catch (Exception e){
            throw new BaseException(DataSourceExceptionEnum.MYSQL_CONNECTION_EXCEPTION.getCode(),
                    DataSourceExceptionEnum.MYSQL_CONNECTION_EXCEPTION.getMessage());
        }
        return true;
    }
}

